package com.kun.sync.processor;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 转化逻辑
 * 
 * @author zjkorder (2018/1/30 9:59)
 */
public class DefaultConvertProcessor extends ConvertProcessor {

	private Map<String, String> convertRule;

	private int[] sqlType;

	private String[] returnParamsSort;

	public DefaultConvertProcessor(Map<String, String> convertRule, int[] sqlType, String[] returnParamsSort) {
		this.convertRule = convertRule;
		this.sqlType = sqlType;
		this.returnParamsSort = returnParamsSort;

		if (convertRule == null) {
			this.convertRule = new HashMap<>();
			for (String params : returnParamsSort) {
				this.convertRule.put(params, params);
			}
		}
	}

	public ParamsType convert(ResultSet resultSet) throws SQLException {

		{
			// 获取字段类型
			if (sqlType == null) {

				Map<String, Integer> resultSetSqlType = new HashMap<>();
				ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
				for (int i = 0; i < resultSetMetaData.getColumnCount(); i++) {
					resultSetSqlType.put(resultSetMetaData.getColumnName(i + 1),
							resultSetMetaData.getColumnType(i + 1));
				}
				int[] sqlType = new int[returnParamsSort.length];
				for (int i = 0; i < returnParamsSort.length; i++) {
					sqlType[i] = resultSetSqlType.get(convertRule.get(returnParamsSort[i]));
				}
				this.sqlType = sqlType;
			}

		}

		Object[] params = new Object[returnParamsSort.length];
		for (int i = 0; i < returnParamsSort.length; i++) {
			params[i] = resultSet.getObject(convertRule.get(returnParamsSort[i]));
		}

		return new ParamsType(params, sqlType);
	}

}
